using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using MammothMicro.SMTPGuard;
using MammothMicro.SmtpGuardFilter.Common;

namespace MammothMicro.SmtpGuardFilter.Filter
{
    /// <summary>
    /// Allows all email addresses addressed to the local domain specified
    /// in the constructor.
    /// </summary>	
    public class LocalRecipientFilter : IEmailFilter {
		
        #region Variables
		
        private string _domain;
        private List<string> _list = new List<string>();
        #endregion
		
        #region Constructors
		
        /// <summary>
        /// Specifies the domain to accept email for.
        /// </summary>
        public LocalRecipientFilter( string domain ) 
        {
            this._domain = domain.ToLower();
        }
		
        public LocalRecipientFilter()
        {
        }
        #endregion

        /// <summary>
        /// Test the email to determine if it should be allowed
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool Accept(MailMessage message)
        {
            return _list.Contains(message.To[0].Address.ToLower());
        }

        public void Reload()
        {
            var path = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            path = path.Remove(0, 6);
            var reader = new StreamReader(path + @"\configuration\localRecipients.txt");
            var text = reader.ReadToEnd().ToLower().ToLower();
            reader.Close();
            const string delimiter = "\r\n";
            var t = text.Split(delimiter.ToCharArray());
            _list =Tools.ClearEmptyItems(t.ToList());
        }
    }
}